﻿using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VideoController : ControllerBase
    {
        private readonly string _baseDir = @"D:\soft\D2";

        /// <summary>
        /// 获取已有录像的日期列表（目录为 yyyy-MM-dd 格式）
        /// </summary>
        [HttpGet("dates")]
        public IActionResult GetAvailableDates()
        {
            if (!Directory.Exists(_baseDir))
                return Ok(new List<string>());

            var dates = Directory
                .GetDirectories(_baseDir)
                .Select(Path.GetFileName)
                .Where(d =>
                    DateTime.TryParseExact(
                        d,
                        "yyyy-MM-dd",
                        CultureInfo.InvariantCulture,
                        DateTimeStyles.None,
                        out _
                    )
                )
                .OrderByDescending(d => d)
                .ToList();

            return Ok(dates);
        }

        /// <summary>
        /// 根据日期获取对应 mp4 文件列表，并返回可播放的 URL
        /// </summary>
        [HttpGet("files")]
        public IActionResult GetFilesByDate([FromQuery] string date)
        {
            if (string.IsNullOrWhiteSpace(date))
                return BadRequest("日期 参数不能为空");

            var dir = Path.Combine(_baseDir, date);

            if (!Directory.Exists(dir))
                return Ok(new List<object>());

            // 获取当前请求的 host 地址，用于生成播放 URL
            var request = HttpContext.Request;
            var baseUrl = $"{request.Scheme}://{request.Host}/api/video/play";

            var files = Directory
                .GetFiles(dir, "*.mp4")
                .Select(f =>
                {
                    var fileName = Path.GetFileName(f);

                    return new
                    {
                        FileName = fileName,
                        FullPath = f,
                        SizeMB = Math.Round(new FileInfo(f).Length / 1024.0 / 1024.0, 2),
                        CreatedTime = System
                            .IO.File.GetCreationTime(f)
                            .ToString("yyyy-MM-dd HH:mm:ss"),
                        Url = $"{baseUrl}?date={date}&fileName={Uri.EscapeDataString(fileName)}",
                    };
                })
                .OrderBy(x => x.FileName)
                .ToList();

            return Ok(files);
        }

        /// <summary>
        /// 按时间范围查询录像
        /// start 和 end 格式示例：2025-10-22 08:00:00
        /// </summary>
        [HttpGet("search")]
        public IActionResult SearchByTimeRange([FromQuery] string start, [FromQuery] string end)
        {
            if (string.IsNullOrWhiteSpace(start) || string.IsNullOrWhiteSpace(end))
                return BadRequest("start 和 end 参数不能为空");

            if (
                !DateTime.TryParseExact(
                    start,
                    "yyyy-MM-dd HH:mm:ss",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out var startTime
                )
                || !DateTime.TryParseExact(
                    end,
                    "yyyy-MM-dd HH:mm:ss",
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out var endTime
                )
            )
                return BadRequest("时间格式错误，必须为 yyyy-MM-dd HH:mm:ss");

            if (endTime < startTime)
                return BadRequest("结束 时间不能小于 开始 时间");

            // 涉及到的日期目录列表
            var dates = new List<string>();
            var tmp = startTime.Date;
            while (tmp <= endTime.Date)
            {
                dates.Add(tmp.ToString("yyyy-MM-dd"));
                tmp = tmp.AddDays(1);
            }

            var results = new List<object>();

            foreach (var date in dates)
            {
                var dir = Path.Combine(_baseDir, date);
                if (!Directory.Exists(dir))
                    continue;

                var files = Directory.GetFiles(dir, "*.mp4");
                foreach (var file in files)
                {
                    var fileName = Path.GetFileNameWithoutExtension(file); // yyyy-MM-dd_HH-mm-ss
                    if (
                        DateTime.TryParseExact(
                            fileName,
                            "yyyy-MM-dd_HH-mm-ss",
                            CultureInfo.InvariantCulture,
                            DateTimeStyles.None,
                            out var fileTime
                        )
                    )
                    {
                        // 文件时间是否在范围内
                        if (fileTime >= startTime && fileTime <= endTime)
                        {
                            var info = new FileInfo(file);
                            results.Add(
                                new
                                {
                                    FileName = info.Name,
                                    FullPath = file,
                                    SizeMB = Math.Round(info.Length / 1024.0 / 1024.0, 2),
                                    CreatedTime = fileTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                }
                            );
                        }
                    }
                }
            }
            return Ok(results.OrderBy(r => ((dynamic)r).CreatedTime).ToList());
        }

        /// <summary>
        /// 删除指定录像文件
        /// </summary>
        [HttpDelete("delete")]
        public IActionResult DeleteFile([FromQuery] string date, [FromQuery] string name)
        {
            if (string.IsNullOrWhiteSpace(date) || string.IsNullOrWhiteSpace(name))
                return BadRequest("date 和 name 参数不能为空");

            var dir = Path.Combine(_baseDir, date);
            if (!Directory.Exists(dir))
                return NotFound("对应日期目录不存在");

            var filePath = Path.Combine(dir, name);
            if (!System.IO.File.Exists(filePath))
                return NotFound("文件不存在");

            try
            {
                System.IO.File.Delete(filePath);
                return Ok("删除成功");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"删除失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 播放指定日期的 mp4 视频
        /// 示例: GET /api/video/play?date=2025-10-22&fileName=2025-10-22_08-30-00.mp4
        /// </summary>
        [HttpGet("play")]
        public IActionResult Play([FromQuery] string date, [FromQuery] string fileName)
        {
            if (string.IsNullOrWhiteSpace(date) || string.IsNullOrWhiteSpace(fileName))
                return BadRequest("日期和文件名不能为空");

            var filePath = Path.Combine(_baseDir, date, fileName);

            if (!System.IO.File.Exists(filePath))
                return NotFound("文件不存在");

            try
            {
                // 打开文件流
                var stream = new FileStream(
                    filePath,
                    FileMode.Open,
                    FileAccess.Read,
                    FileShare.Read
                );
                // 返回视频流
                return File(stream, "video/mp4", enableRangeProcessing: true);
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"播放失败: {ex.Message}");
            }
        }
    }
}
